<template>
	<div v-loading="loading" class="warningInfo">
		<div class="warningInfo-header">
			<div class="warningInfo-header-flex">
				<img class="warningInfo-header-img" src="@/assets/images/warningInfo/warning.png" alt="404" />
				<div>
					<div class="warningInfo-header-ch">预警综合信息控制台</div>
					<div class="warningInfo-header-en">Warning integrated information console</div>
				</div>
			</div>
			<div class="warningInfo-header-flex">
				<jk-full-screen-button v-if="fromPage !== 'largeScreen'" class-name="warningInfo"></jk-full-screen-button>

				<img class="warningInfo-header-img2" src="@/assets/images/warningInfo/timeIcon3.png" alt="404" />
				<div>
					<div class="warningInfo-header-time">{{ currentDate }}</div>
					<div class="warningInfo-header-timeHHssmm">{{ currentTime }}</div>
				</div>

			</div>

		</div>

		<div class="warningInfo-main">
			<div v-if="hasWarning" class="warningInfo-main-left">
				<!--总数-->
				<div class="warningInfo-main-left-count">
					<div v-for="item in filteredStateList" :key="item.title" class="warningInfo-main-left-countStyle">
						<div class="warningInfo-main-left-icon">
							<img width="26" :src="`${item.icon}`" alt="404" />
						</div>
						<div>
							<div>{{ item.name === '关机'? '网络异常':item.name }}</div>
							<div><div class="warningInfo-main-left-value">{{ item.count }}</div><span>个</span></div>
						</div>
					</div>
				</div>
				<!--				<div class="warningInfo-main-left-type">-->
				<!--					<div v-for="item in filteredStateList" :key="item.title" class="warningInfo-main-left-type-flex">-->
				<!--						<img width="18" :src="`${item.typeIcon}`" alt="404" />-->
				<!--						<div>{{ item.name === '关机'? '网络异常':item.name }}</div>-->
				<!--					</div>-->
				<!--					&lt;!&ndash;  查询下拉&ndash;&gt;-->
				<!--					<kan-ban-dropdown-->
				<!--						v-model="searchParams.workshopId"-->
				<!--						:option-list="workshopList"-->
				<!--						size="mini"-->
				<!--						class="item-gap"-->
				<!--						@change="onSelectDropdown"-->
				<!--					></kan-ban-dropdown>-->
				<!--				</div>-->
				<warning-list ref="scrollContainer" :data="stateList" @MachineItem="onMachineItem" />
			</div>
			<!-- 右侧-->
			<div class="warningInfo-main-right">
				<div class="warningInfo-regional">
					<regional-temperature :data="regionalTemperatureData" />
				</div>
				<div class="warningInfo-alert">
					<warning-alert :data="monitorList" />
				</div>
			</div>

		</div>

		<detail-dialog
			ref="detailDialog"
			:data-item="dataItem"
			:dialog-state="detailDialogState"
			@on-visible-change="onVisibleChangeOfDetailDialog"
		></detail-dialog>

	</div>
</template>

<script>
    import {
        machineManagerAreaSingleGetTemNum, getStateMonitor, getCountMonitor
    } from '@/api/production/kanBan';
    import warnIcon from '@/assets/images/warningInfo/warnIcon.png';
    import warnIcon1 from '@/assets/images/warningInfo/warnIcon1.png';
    import warnIcon3 from '@/assets/images/warningInfo/warnIcon3.png';
    import warnIcon2 from '@/assets/images/warningInfo/warnIcon2.png';
    import warnIcon4 from '@/assets/images/warningInfo/warnIcon4.png';
    import warnIcon5 from '@/assets/images/warningInfo/warnIcon5.png';
    import warnIcon6 from '@/assets/images/warningInfo/warnIcon6.png';
    import typeIcon from '@/assets/images/warningInfo/contentIcon/warn.png';
    import typeIcon1 from '@/assets/images/warningInfo/contentIcon/warn1.png';
    import typeIcon2 from '@/assets/images/warningInfo/contentIcon/warn2.png';
    import typeIcon3 from '@/assets/images/warningInfo/contentIcon/warn3.png';
    import typeIcon4 from '@/assets/images/warningInfo/contentIcon/warn4.png';
    import typeIcon5 from '@/assets/images/warningInfo/contentIcon/warn5.png';
    import typeIcon6 from '@/assets/images/warningInfo/contentIcon/warn6.png';
    import kanBanDropdown from '@/views/productionMonitor/kanBan/componenst/kan-ban-dropdown/index.vue';
    export default {
        props: {
            fromPage: {
                type: String,
                default: ''
            }
        },
        components: {
            kanBanDropdown,
            WarningList: () => import('@/views/productionMonitor/warningInfo/components/warningList.vue'),
            RegionalTemperature: () => import('@/views/productionMonitor/warningInfo/components/regionalTemperature.vue'),
            WarningAlert: () => import('@/views/productionMonitor/warningInfo/components/warningAlert.vue'),
            detailDialog: () => import('./components/detail-dialog.vue')
        },
        data() {
            return {
                regionalTemperatureData: [],
                currentDate: '',
                currentTime: '',
                detailDialogState: false,
                loading: true,
                hasWarning: true,
                workshopList: [],
                monitorList: [],
                stateList: [],
                warningIcons: {
                    '-1': { icon: warnIcon, typeIcon: typeIcon },
                    '2': { icon: warnIcon1, typeIcon: typeIcon1 },
                    '3': { icon: warnIcon2, typeIcon: typeIcon2 },
                    '4': { icon: warnIcon4, typeIcon: typeIcon4 },
                    '5': { icon: warnIcon5, typeIcon: typeIcon5 },
                    '6': { icon: warnIcon3, typeIcon: typeIcon3 },
                    '7': { icon: warnIcon6, typeIcon: typeIcon6 }
                },
                dataItem: {},
                processList: [],
                searchParams: {
                    workshopId: -1
                },
                timer: null,
                dataUpdateTimer: null, // 新增的定时器，用于两秒循环请求
                firstLoad: true // 新增标志变量，判断是否为第一次调用
            };
        },
        computed: {
            filteredStateList() {
                return this.stateList.map(item => ({
                    ...item,
                    ...this.warningIcons[item.state]
                }));
            }
        },
        methods: {

            setLoading() {
                if (this.firstLoad) {
                    this.loading = true;
                }
            },
            clearLoading() {
                if (this.firstLoad) {
                    this.loading = false;
                    this.firstLoad = false;
                }
            },

            // 区域温湿度
            getRegionalData() {
                this.setLoading();
                return machineManagerAreaSingleGetTemNum().then(res => {
                    if (res.data.status === 200) {
                        const data = res.data.res;

                        this.regionalTemperatureData = data.flatMap(item =>
                            item.itemList.map(subItem => ({
                                ...item, // 复制原始对象的属性
                                processName: subItem.areaName, // 使用 areaName 作为新的 processName
                                itemList: [subItem] // 将 itemList 替换为单个元素的数组
                            }))
                        );
                        this.clearLoading();
                    }
                });
            },
            async onSelectDropdown(e) {
                await this.getListRequest();
            },
            // 预警列表数据
            getListRequest() {
                this.setLoading();
                if (!this.searchParams.workshopId) return;
                const arr = this.searchParams.workshopId === -1 ? [] : [this.searchParams.workshopId];
                return getStateMonitor({
                    workshopIds: arr,
                    processCode: ''
                }).then(res => {
                    if (res.data.status === 200) {
                        this.processList = res.data.res.processList || []; // 全部滚动列表
                        this.stateList = res.data.res.stateList || []; // 全部滚动列表
                        this.hasWarning = this.stateList.some(state => state.count !== 0); // 判断是否有任意一个 state 的 count 不为 0
                        this.clearLoading();
                    }
                });
            },
            // 预警列表数据
            getCountMonitorRequest() {
                this.setLoading();
                // if (!this.searchParams.workshopId) return;
                // const arr = this.searchParams.workshopId === -1 ? [] : [this.searchParams.workshopId];
                return getCountMonitor().then(res => {
                    if (res.data.status === 200) {
                        this.monitorList = res.data.res || []; // 全部滚动列表
                        this.clearLoading();
                    }
                });
            },

            runScroll() {
                clearInterval(this.timer);
                this.timer = setInterval(() => {
                    const scrollContainer = this.$refs.scrollContainer.$el;
                    if (scrollContainer.scrollHeight > scrollContainer.clientHeight) {
                        if (scrollContainer.scrollTop + scrollContainer.clientHeight >= scrollContainer.scrollHeight) {
                            scrollContainer.scrollTop = 0; // 回到顶部
                        } else {
                            scrollContainer.scrollTop += 1; // 每次移动1px
                        }
                    }
                }, 60);
            },

            onVisibleChangeOfDetailDialog(e) {
                this.detailDialogState = e;
            },
            onMachineItem(e) {
                const workshopItem = this.workshopList.find(x => x.id === this.searchParams.workshopId) || {};
                this.dataItem = {
                    ...e,
                    workshopId: workshopItem.id,
                    workshopCode: workshopItem.code,
                    workshopName: workshopItem.name
                };
                this.detailDialogState = true;
            },

            // 时间更新
            updateTime() {
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const day = String(now.getDate()).padStart(2, '0');
                const date = `${year}/${month}/${day}`;

                const hours = String(now.getHours()).padStart(2, '0');
                const minutes = String(now.getMinutes()).padStart(2, '0');
                const seconds = String(now.getSeconds()).padStart(2, '0');
                const time = `${hours}:${minutes}:${seconds}`;

                const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
                const weekday = weekdays[now.getDay()];

                this.currentDate = `${date} ${weekday}`;
                this.currentTime = time;
            },
            startDataUpdateInterval() {
                this.dataUpdateTimer = setInterval(() => {
                    this.getRegionalData();
                    this.getListRequest();
                    // this.getCountMonitorRequest()
                }, 2000); // 每两秒调用一次
            },
            clearDataUpdateInterval() {
                if (this.dataUpdateTimer) {
                    clearInterval(this.dataUpdateTimer);
                    this.dataUpdateTimer = null;
                }
            },
            startTimers() {
                this.updateTime(); // 初始化时间
                this.timeUpdateTimer = setInterval(this.updateTime, 1000); // 时间更新
                this.runScroll(); // 启动滚动
                this.startDataUpdateInterval(); // 启动数据更新
            },
            clearTimers() {
                clearInterval(this.timeUpdateTimer); // 清理时间更新定时器
                clearInterval(this.timer); // 清理滚动定时器
                this.clearDataUpdateInterval(); // 清理数据更新定时器
            }

        },
        created() {
            this.startTimers();
            this.workshopList = [
                { id: -1, name: '全部' },
                ...this.$store.state.user.userWorkshop.workshopList
            ];

            this.getRegionalData(); // 区域温湿度
            this.getListRequest(); // 预警全部信息
            this.getCountMonitorRequest(); // 设备支数异常提醒
        },

        mounted() {
        },
        destroyed() {
            this.clearTimers();
        }

    };
</script>

<style scoped lang="scss">
@import "index";

</style>
